import { mapMutations, mapActions, mapState } from "vuex";
import { typeClassName } from "@/pages/config/classNameMap";
import _ from "lodash";
const requireComponent = require.context("./", true, /[A-Z]\w+\.(vue)$/);
const comp = {};
requireComponent.keys().forEach((fileName) => {
  if (fileName != "./index.vue") {
    const componentConfig = requireComponent(fileName);
    const name = componentConfig.default.name;
    const componentName = _.camelCase(
      name
        .split("/")
        .pop()
        .replace(/\.\w+$/, "")
    );
    comp[componentName] = componentConfig.default || componentConfig;
  }
});
Object.keys(comp).map((key) => {
  comp[key].components = comp;
});
export default {
  components: comp,
  data() {
    return {
      vms: {}, //页面组件vue实例
      completeLoad: false,
      me: this,
      watchs: [],
      //模型
      models: {
        //模型

        technologyParams: {
          ...typeClassName["technologyParams"],
        },
        product: {
          ...typeClassName["product"],
        },
        equipment: {
          ...typeClassName["equipment"],
        },
        collectionPoint: {
          ...typeClassName["collectionPoint"],
        },
      },
      equipOptions: [],
      productOptions: [],
      parentId: "",
      equipId: "",
      ids:"",
      dataSet: {
        //数据集
        treeData: [],
        currentData: {},
        formData: {
          sf_code: "",
          sf_name: "",
        },
        tableData: [],
        productTreeBindData: {},
        treeCurrentData: [],
        tableData: [],
        pointData: [],
      },
    };
  },
  provide() {
    return {
      anc: this,
    };
  },
  computed: {},
  created() {
    Object.keys(this.models).map((k) => {
      this.models[k].clz = this.$modelObject.create(this.models[k].modelType);
      this.models[k].clzs = this.$modelObject.create(
        this.models[k].modelType + "Collection"
      );
    });
    this.getReturnTrue();
  },
  mounted() {
    this.watchs.map((item) => {
      this.$watch(item.target, item.fn, { deep: item.deep });
    });
    this.$nextTick(() => {
      this.unwatch = this.$watch("vms", (newValue, oldValue) => {
        let flag = true;
        Object.keys(comp).map((k) => {
          if (!Object.keys(this.vms).includes(k)) {
            flag = false;
          }
        });
        this.completeLoad = flag;
      });
      // this.init();
      if (process.env.NODE_ENV === "development") {
        console.log({
          me: this,
          vms: this.vms,
          completeLoad: this.completeLoad,
        });
      }
    });
  },
  destroyed() {
    this.unwatch();
  },
  methods: {
    init() {},
    loadPage(pageNavigation, filter) {
      let newFilter = {
        ...filter,
        className: this.models.technologyParams.className,
        type: this.models.technologyParams.type,
      }

      let hierFilter = this._$setFilteStr(newFilter, false);
      hierFilter = hierFilter +`&& id in (${this.ids})`
      this._$queryByPage(
        this.models["technologyParams"].clzs,
        pageNavigation,
        hierFilter,
        "",
        "updateTime",
        false
      ).then((res) => {
        this.dataSet.tableData =
          this.models["technologyParams"].clzs.valueRecords;
      });
    },
    /**
     * 新增-弹窗显示
     */
    handleCreate() {
      if (this.dataSet.treeCurrentData.length > 0) {
        this.vms.createView.resetFields();
        this.dataSet.formData["productName"] =
          this.dataSet.treeCurrentData[0].data.sf_name;
        this.dataSet.formData["productCode"] =
          this.dataSet.treeCurrentData[0].data.id;
        this.dataSet.formData["equName"] = this.dataSet.treeCurrentData[0].data.equName;
        this.dataSet.formData['imgNumber'] = this.dataSet.treeCurrentData[0].data.imgNumber
          this._modalShow("createModal");
         
      } else {
        this.$Message.info("请选择产品");
      }
    },
    /**
     * 查看-弹窗显示
     * @param {*} row
     */
    handleDetail(row) {
      this._modalShow("detailModal");
      this.dataSet.currentData = row;
      this.dataSet.formData = row.values;
    },
    /**
     * 编辑-弹窗显示
     * @param {*} row
     */
    handleEdit(row) {
      this._modalShow("editModal");
      this.dataSet.currentData = row;
      this.dataSet.formData = row.values;
    },
    /**
     * 删除单行
     * @param {行数据} row
     * @param {索引} index
     */
    handleDelete(row, index) {
      let _this = this;
      this._$deleteConfirm(() => {
        _this
          ._$deleteByIds(_this.models.technologyParams.clzs, [String(row.id)])
          .then((res) => {
            this.querySpecificationByProductId(
              this.dataSet.treeCurrentData[0].data
            );
          });
      });
    },
    handleDeleteMultiple(selection) {
      let _this = this;
      this._$deleteConfirm(() => {
        let ids = selection.map((item) => String(item.row.link.linkId));
        _this
          ._$deleteByIds(_this.models.technologyParams.clzs, ids)
          .then((res) => {
            _this.vms.mainTable.navigation.page.pageNumber = 1;
            this.querySpecificationByProductId(
              this.dataSet.treeCurrentData[0].data
            );
          });
      });
    },
    // 新增确认
    createModalOk(btn) {
      this._$validateAll([this.vms.createView], (valid) => {
        btn.loading = false;
        if (valid) {
          // this.dataSet.formData.productName = this._$getOptionValue(
          //   this.productOptions,
          //   this.dataSet.formData.productCode
          // );
          this.dataSet.formData.byHand = "手动创建"
          // this.dataSet.formData["equName"] = this._$getOptionValue(
          //   this.equipOptions,
          //   this.dataSet.formData.equCode
          // );
          // this.dataSet.formData["equipId"] = this.dataSet.treeCurrentData[0].data.equCode;
          let formData = this.$modelObject.getTpl(
            this.models.technologyParams.modelType
          );
          formData.containerId =
            this.dataSet.productTreeBindData.hier.containerId;
          formData.className = this.models.technologyParams.className;
          formData.type = this.models.technologyParams.type;
          formData.name = +new Date();
          formData.values = this.dataSet.formData;
          // this.dataSet.
          this.$api.inspection.addTechnologyParams(formData).then((flag) => {
            this._modalClose("createModal");
            this.querySpecificationByProductId(
              this.dataSet.treeCurrentData[0].data
            );
          });
        } else {
          btn.loading = false;
          this.$Message.info("请填写必填内容");
        }
      });
    },
    // 编辑确认
    editModalOk(btn) {
      this.vms.editView.validate((valid) => {
        btn.loading = false;
        if (valid) {
          // this.dataSet.formData["productName"] = this._$getOptionValue(
          //   this.productOptions,
          //   this.dataSet.formData.productCode
          // );
          // this.dataSet.formData["equName"] = this._$getOptionValue(
          //   this.equipOptions,
          //   this.dataSet.formData.equCode
          // );
          this.dataSet.formData["equipId"] = this.dataSet.treeCurrentData[0].data.equCode;
          this.dataSet.currentData.values = {
            ...this.dataSet.formData,
          };
          this.models.technologyParams.clz.setRecord(this.dataSet.currentData);
          this.models.technologyParams.clz.updateById().then((flag) => {
            if (flag) {
              this._modalClose("editModal");
              this.querySpecificationByProductId(
                this.dataSet.treeCurrentData[0].data
              );
            } else {
              this._modalClose("editModal");
            }
          });
        } else {
          btn.loading = false;
          this._$requireInfo();
        }
      });
    },
    change(item, value) {},
    treeSelect(item, data) {
      this.dataSet.treeCurrentData = data;
      this.dataSet.tableData = [];
      if (data.length == 0) {
        return;
      }
      // this.equipId = item.equipId;
      // this.getPointerPosition();
      this.querySpecificationByProductId(item);
      // this.loadPage(this.vms.mainTable.navigation.page,{equipmentTypeCode:item.id})
    },
    querySpecificationByProductId(item) {
      this.$api.inspection.querySpecificationByProductId(item).then((res) => {
        this.dataSet.productTreeBindData = res;
        this.parentId = this._$getHierItemField(res.hier, "工艺参数", "nodeId");
        if (!this.parentId) {
          return;
        }
        let arr = this.dataSet.productTreeBindData.hier.content.filter(
          (item) => item.parentId == this.parentId
        );
        if (arr.length == 0) {
          this.vms.mainTable.navigation.page.total = 0
          return
        }
        this.ids = arr.map(item => item.link.linkId).join(",")
        this.loadPage(this.vms.mainTable.navigation.page, {})
        // this.dataSet.tableData =
        //   this.dataSet.productTreeBindData.hier.content.filter(
        //     (item) => item.parentId == this.parentId
        //   ); // 进入页面点击设备存储所有的选项
        // if (this.dataSet.tableData.length > 0) {
        //   this.dataSet.tableData = this.dataSet.tableData.map((item) => {
        //     return {
        //       ...item,
        //       values: {
        //         ...item.values,
        //       },
        //       ...item.values,
        //     };
        //   });
        // }
      });
    },
    getReturnTrue() {
      Promise.all([this.getEquipOptions(), this.getProductOptions()]).then(
        (res) => {
          // this.result = res[0];
          this.vms.mainTable.beforePageInit();
          this.vms.createView.beforePageInit();
          this.vms.editView.beforePageInit();
          this.vms.detailView.beforePageInit();
        }
      );
    },
    getEquipOptions() {
      let data = {
        className: this.models.equipment.className,
        type: this.models.equipment.type,
      };
      this.equipOptions = [];
      return this._$query(this.models.equipment.clzs, data).then((res) => {
        if (res) {
          this.models.equipment.clzs.records.forEach((item) => {
            this.equipOptions.push({
              label: item.values.sf_name,
              value: String(item.id),
            });
          });
          return true;
        } else {
          return false;
        }
      });
    },
    getProductOptions() {
      let data = {
        className: this.models.product.className,
        type: this.models.product.type,
      };
      this.productOptions = [];
      return this._$query(this.models.product.clzs, data).then((res) => {
        if (res) {
          this.models.product.clzs.records.forEach((item) => {
            this.productOptions.push({
              label: item.values.sf_name,
              value: String(item.id),
            });
            this.dataSet.treeData.push({
              id: item.id,
              parentId: "root",
              name: item.values.sf_name,
              sf_name: item.values.sf_name,
              equipId: item.values.equipId,
              imgNumber: item.values.imgNumber,
              equName: item.values.equipName
            });
          });
          return true;
        } else {
          return false;
        }
      });
    },
    // getPointerPosition() {
    //   let data = {
    //     className: this.models.collectionPoint.className,
    //     type: this.models.collectionPoint.type,
    //     equipmentTypeCode: this.equipId,
    //   };
    //   this._$query(this.models.collectionPoint.clzs, data).then((flag) => {
    //     if (flag) {
    //       this.models.collectionPoint.clzs.records.forEach((item) => {
    //         this.dataSet.pointData.push({
    //           label: item.values.paramName,
    //           value: String(item.id),
    //         });
    //       });
    //     }
    //   });
    // },
  },
};
